console.log("PWA auto update Server started");
const fs = require("fs");
const WebSocket = require("ws");
const wss = new WebSocket.Server({ port: 8010 });

wss.on("connection", function connection(ws) {
  ws.on("message", function incoming(data) {
    console.log("Received from client: %s", data);
    if (data == "ping") {
      ws.send("pong");
    } else if (data == "query") {
      const data = fs.readFileSync(__dirname + "/erp-version");
      ws.send(data.toString());
    } else if (data == "update") {
      const data = fs.readFileSync(__dirname + "/erp-version");
      const version = Number(data) + 1;
      fs.writeFileSync(__dirname + "/erp-version", version);
      wss.clients.forEach(function each(client) {
        if (client.readyState === WebSocket.OPEN) {
          client.send(version);
        }
      });
    } else {
      client.send(data);
    }
  });
});